<?php

namespace App\Repository;

use App\Models\Admin\AdminUsers;
use App\Models\Anchor\AnchorAuthorModel;
use App\Models\Anchor\AnchorModel;
use App\Models\Anchor\AnchorWorksModel;
use App\Models\Orders\OrdersModel;
use App\Models\Orders\OrdersUserModel;
use App\Models\Service\ServiceCallModel;
use App\Repository\Anchor\AnchorStatsRepository;
use Illuminate\Support\Facades\Cache;

class DashboardRepository extends BaseRepository
{
    public function __construct()
    {

        parent::__construct();
    }

    protected function getWhereArray($params = [])
    {
        $loginUserShopId = $params['user']['shop_id'];
        $ModelOrders = new OrdersModel();
        $ModelOrdersUser = new OrdersUserModel();
        $ModelAnchorAuthor = new AnchorAuthorModel();
        $where = [];
        //创建时间条件
        if (isset($params['dateRange']) && !empty($params['dateRange'])) {
            $params['dateRange'] = [date('Y-m-d', strtotime($params['dateRange'][0])), date('Y-m-d', strtotime($params['dateRange'][1])) . ' 23:59:59'];
            $where['between']['a.created_at'] = $params['dateRange'];
        } else {
            $where['between']['a.created_at'] = [date('Y-m-d'), date('Y-m-d H:i:s')];
        }
//        客服条件
        if (isset($params['service_user_id']) && !empty($params['service_user_id'])) {
            if (is_array($params['service_user_id'])) {
                if (count($params['service_user_id']) > 1) {
                    $where['in']['a.service_user_id'] = $params['service_user_id'];
                } else {
                    $where['eq']['a.service_user_id'] = $params['service_user_id'][0];
                }
            } else {
                $where['eq']['a.service_user_id'] = $params['service_user_id'];
            }
        }
//        分销商
        if (isset($params['shop_id']) && !empty($params['shop_id'])) {
            if (is_array($params['shop_id'])) {
                if (count($params['shop_id']) > 1) {
                    $where['in']['a.shop_id'] = $params['shop_id'];
                } else {
                    $where['eq']['a.shop_id'] = $params['shop_id'][0];
                }
            } else {
                $where['eq']['a.shop_id'] = $params['shop_id'];
            }
        } else {
            $where['eq']['a.shop_id'] = $loginUserShopId;
        }
//        商品条件
        if (isset($params['goods_id']) && !empty($params['goods_id'])) {
            if (is_array($params['goods_id'])) {
                if (count($params['goods_id']) > 1) {
                    $where['in']['a.goods_id'] = $params['goods_id'];
                } else {
                    $where['eq']['a.goods_id'] = $params['goods_id'][0];
                }
            } else {
                $where['eq']['a.goods_id'] = $params['goods_id'];
            }
        }
//        订单来源
        if (isset($params['source']) && !empty($params['source'])) {
            if (is_array($params['source'])) {
                if (count($params['source']) > 1) {
                    $where['in']['b.source'] = $params['source'];
                } else {
                    $where['eq']['b.source'] = $params['source'][0];
                }
            } else {
                $where['eq']['b.source'] = $params['source'];
            }
        }
//        主播要特殊处理
        if (isset($params['anchor_id']) && !empty($params['anchor_id'])) {
            $anchorWhere = [];
            if (is_array($params['anchor_id'])) {
                if (count($params['anchor_id']) > 1) {
                    $anchorWhere['in']['anchor_id'] = $params['anchor_id'];
                } else {
                    $anchorWhere['anchor_id'] = $params['anchor_id'][0];
                }
            } else {
                $anchorWhere['anchor_id'] = $params['anchor_id'];
            }

            $authorIds = [];
            foreach ($ModelAnchorAuthor->searchWhere($anchorWhere)->select(['author_id'])->cursor() as $row) {
                $authorIds[] = $row->author_id;
            }
        }
//        达人条件
        if (isset($params['author_id']) && !empty($params['author_id'])) {
//            上面的主播里是否有查询到达人
            if (!isset($authorIds)) {
                $authorIds = [];
            }
            if (is_array($params['author_id'])) {
                $authorIds = array_merge($authorIds, $params['author_id']);
            } else {
                $authorIds[] = $params['author_id'];
            }
            if (count($authorIds) > 1) {
                $where['in']['b.author_id'] = $authorIds;
            } else {
                $where['eq']['b.author_id'] = $authorIds[0];
            }
        }
        if (isset($params['first_money']) && $params['first_money'] != '') {
            $firstMoneyList = config('card.firstMoneyList');
            $firstMoneyItemKey = intval($params['first_money']);
            $firstMoneyItem = $firstMoneyList[$firstMoneyItemKey];
            if ($firstMoneyItem['symbol'] != 'between') {
                $where[$firstMoneyItem['symbol']]['a.first_money'] = $firstMoneyItem['value'];
            } else {
                $where['between']['a.first_money'] = $firstMoneyItem['value'];
            }
//            print_r($where);
        }
        return $where;
    }

    // 同一个页里面查询条件都是一样的,所以它生成的key也是一样的
    protected function getWhereCacheKey($whereArray = [])
    {
        return md5(serialize($whereArray));
    }

    protected function getWhereOrdersData($where, $fields = [])
    {
        if (empty($fields)) {
            $fields = [
                'a.id',
                'a.ordersno',
                'a.status',
                'a.first_status',
                'a.first_status_at',
                'a.first_money',
                'a.card_status',
                'a.goods_name',
                'a.goods_id',
                'a.express_number',
                'a.product_id',
                'a.product_name',
                'a.product_code',
                'a.shop_id',
                'a.activat_at',
                'a.is_online',
                'a.rebate_status',
                'a.rebate_user_id',
                'a.review_user_id',
                'a.review_status',
                'a.service_user_id',
                'a.activat_status',
                'a.three_msg',
                'a.review_activat_user_id',
                'a.review_first_user_id',
                'a.passing_money',
                'b.pay_identity', 'b.pay_phone',
                'b.post_province',
                'b.post_city',
                'b.post_area', 'b.post_address',
                'b.author_id',
                'b.author_name',
                'b.author_commission',
                'b.sex',
                'b.age',
            ];
        }
        $cacheFile = '_dashboard' . $this->getWhereCacheKey($where);
        $ModelOrders = new OrdersModel();
        $ModelOrdersUser = new OrdersUserModel();
        $rows = Cache::get($cacheFile);
        if (empty($rows)) {
            foreach ($ModelOrders->from($ModelOrders->getTable(), 'a')
                         ->leftJoin($ModelOrdersUser->getTable() . ' AS b', 'a.ordersno', '=', 'b.orderno')
                         ->searchWhere($where)
                         ->select($fields)
//                     ->page($page, $limit)
                         ->orderByDesc('a.id')
                         ->cursor() as $row) {
                $rows[$row['ordersno']] = $row;
            }
//            echo $this->getLastSql();
            // 只缓存订单表数据
            Cache::put($cacheFile, $rows, 120);
        }
        return empty($rows) ? [] : $rows;
    }

    public function index($params = [], $page = 1, $limit = 10)
    {
        switch ($params['dataN']) {
            case 8:
                $data = $this->data8($params);
                break;
            case 7:
                $data = $this->data7($params);
                break;
            case 6:
                $data = $this->data6($params);
                break;
            case 5:
                $data = $this->data5($params);
                break;
            case 4:
                $data = $this->data4($params);
                break;
            case 3:
                $data = $this->data3($params);
                break;
            case 2:
                $data = $this->data2($params);
                break;
            default:
                $data = $this->data1($params);
                break;
        }
        return $data;
    }

    public function data1($params = [])
    {
        $loginUserId = $params['user']['id'];
//        $loginUserShopId = $params['user']['shop_id'];
//        $ModelOrders = new OrdersModel();
//        $ModelOrdersUser = new OrdersUserModel();
//        $ModelAnchorAuthor = new AnchorAuthorModel();
        $where = $this->getWhereArray($params);
        $count = 0;
        $data1 = [
            'total' => 0,
//            提交订单
            'a' => 0,
            'ar' => 0,
//            发货订单
            'b' => 0,
            'br' => 0,
//            跟进中
            'c' => 0,
            'cr' => 0,
//            失败订单
            'd' => 0,
            'dr' => 0,
//            激活订单
            'e' => 0,
            'er' => 0,
//            充值订单
            'f' => 0,
            'fr' => 0,
//            充值达标
            'g' => 0,
            'gr' => 0,
            'g1' => 0,
            'gr1' => 0,
            'g2' => 0,
            'gr2' => 0,
            'g3' => 0,
            'gr3' => 0,
        ];
        $orderRows = $this->getWhereOrdersData($where);
        foreach ($orderRows as $row) {
            $data1['total'] += 1;
//排除50 => '异常单',51 => '取消单',60 => '失败单',0 => '提交中',都算提交上游
            if (!in_array($row->status, [0, 50, 51, 60])) {
//                    提交上游
                $data1['a'] += 1;
            }
            //已发货
            if (in_array($row->status, [20, 30, 40, 41])) {
                $data1['b'] += 1;
            }
            // 失败订单
            if (in_array($row->status, [50, 51, 60])) {
                $data1['d'] += 1;
//                    图表内容
                if (empty($row->three_msg)) {
                    $row->three_msg = '其它';
                }
                $md5ThreeMsg = md5($row->three_msg);

            }
//                    充值达标
            if (intval($row['passing_money']) > 0 && (intval($row['first_money']) >= intval($row['passing_money']))) {
                $data1['g'] += 1;
            }
//                    激活订单
            if ($row['activat_status'] == 1) {
                $data1['e'] += 1;
            }
//                    已充值订单
            if (intval($row['first_status']) == 1) {
                $data1['f'] += 1;
            }
            if(!empty($row['first_money']) && intval($row['first_money'])>0  && intval($row['first_money']) < 100){
                $data1['g1'] += 1;
            }
            if(!empty($row['first_money']) && intval($row['first_money']) >= 100){
                $data1['g2'] += 1;
            }
            if(!empty($row['first_money']) && intval($row['first_money']) >= 200){
                $data1['g3'] += 1;
            }
//                    跟进中
            if ($row['service_user_id'] >= 0) {
                $data1['c'] += 1;
            }
        }
        return $this->returnMsg(200, '查询成功', $data1, $count);
    }

    public function data2($params = [])
    {
        $where = $this->getWhereArray($params);
        $count = 0;
        $orderRows = $this->getWhereOrdersData($where);
        $authorIds = [];
        foreach ($orderRows as $row) {
            $authorIds[] = $row->author_id;
        }
        $data2 = $this->parseAnchorData($params, $authorIds);
        return $this->returnMsg(200, '查询成功', $data2, $count);
    }

    public function data3($params = [])
    {
        $where = $this->getWhereArray($params);
        $count = 0;
        $orderRows = $this->getWhereOrdersData($where);
        $rows = [];
        foreach ($orderRows as $row) {
            $rows[] = $row;
        }
        $data3 = $this->kefuData($rows);
        return $this->returnMsg(200, '查询成功', $data3, $count);
    }

    public function data4($params = [])
    {
        $where = $this->getWhereArray($params);
        $count = 0;
//       失败单图表内容
        $data4 = [
            'total' => 0
        ];
        $orderRows = $this->getWhereOrdersData($where);
        $authorIds = [];
        foreach ($orderRows as $row) {
            // 失败订单
            if (in_array($row->status, [50, 51, 60])) {
//                    图表内容
                $data4['total'] += 1;
                if (empty($row->three_msg)) {
                    $row->three_msg = '其它';
                }
                $md5ThreeMsg = md5($row->three_msg);
                if (!isset($data4[$md5ThreeMsg])) {
                    $data4[$md5ThreeMsg]['name'] = $row->three_msg;
                    $data4[$md5ThreeMsg]['count'] = 1;
                } else {
                    $data4[$md5ThreeMsg]['count'] += 1;
                }
            }

        }
        return $this->returnMsg(200, '查询成功', $data4, $count);
    }

    public function data5($params = [])
    {
        $where = $this->getWhereArray($params);


        $count = 0;
        $orderRows = $this->getWhereOrdersData($where);
//        男女比例图表
        $data5 = [
            'total' => 0
        ];
        $authorIds = [];
        foreach ($orderRows as $row) {
            $data5['total'] += 1;
            if (isset($data5[$row->sex])) {
                $data5[$row->sex] += 1;
            } else {
                $data5[$row->sex] = 1;
            }

        }
        return $this->returnMsg(200, '查询成功', $data5, $count);
    }

    public function data6($params = [])
    {
        $where = $this->getWhereArray($params);


        $count = 0;
        $orderRows = $this->getWhereOrdersData($where);

//      年龄图表
        $data6 = [
            'total' => 0
        ];
        foreach ($orderRows as $row) {

//                    跟进中

            if (!empty($row->age)) {
                $data6['total'] += 1;
                if ($row->age <= 23) {
                    if (isset($data6['1_23'])) {
                        $data6['1_23'] += 1;
                    } else {
                        $data6['1_23'] = 1;
                    }
                } else if ($row->age >= 24 && $row->age <= 30) {
                    if (isset($data6['24_30'])) {
                        $data6['24_30'] += 1;
                    } else {
                        $data6['24_30'] = 1;
                    }
                } else if ($row->age >= 31 && $row->age <= 40) {
                    if (isset($data6['31_40'])) {
                        $data6['31_40'] += 1;
                    } else {
                        $data6['31_40'] = 1;
                    }
                } else if ($row->age >= 41 && $row->age <= 50) {
                    if (isset($data6['41_50'])) {
                        $data6['41_50'] += 1;
                    } else {
                        $data6['41_50'] = 1;
                    }
                } else if ($row->age >= 51 && $row->age <= 59) {
                    if (isset($data6['51_60'])) {
                        $data6['51_60'] += 1;
                    } else {
                        $data6['51_60'] = 1;
                    }
                } else if ($row->age >= 60) {
                    if (isset($data6['60+'])) {
                        $data6['60+'] += 1;
                    } else {
                        $data6['60+'] = 1;
                    }
                }
            }


        }

        return $this->returnMsg(200, '查询成功', $data6, $count);
    }

    public function data7($params = [])
    {
        $where = $this->getWhereArray($params);

        $count = 0;
        $orderRows = $this->getWhereOrdersData($where);
        //      省份图表
        $data7 = [
            'total' => 0
        ];
        foreach ($orderRows as $row) {
            if (!empty($row->post_province)) {
                $data7['total'] += 1;
                if (isset($data7[$row->post_province])) {
                    $data7[$row->post_province] += 1;
                } else {
                    $data7[$row->post_province] = 1;
                }
            }
        }
        return $this->returnMsg(200, '查询成功', $data7, $count);
    }

    public function data8($params = [])
    {

        $where = $this->getWhereArray($params);
        $count = 0;
        $orderRows = $this->getWhereOrdersData($where);
        $data8 = [];
        foreach ($orderRows as $row) {

            if (isset($data8[$row->product_code]['total'])) {
                $data8[$row->product_code]['total'] += 1;
            } else {
//                数据初始货
                $data8[$row->product_code] = [
                    'total' => 1,
                    'name' => $row->product_name,
                    'a' => 0, //提交上游
                    'b' => 0,//已发货
                    'c' => 0,//失败订单
                    'd' => 0,//激活
                    'e' => 0, //已充值
                ];
            }


//排除50 => '异常单',51 => '取消单',60 => '失败单',0 => '提交中',都算提交上游
            if (!in_array($row->status, [0, 50, 51, 60])) {
                $data8[$row->product_code]['a'] += 1;
            }
            //已发货
            if (in_array($row->status, [20, 30, 40, 41])) {
                $data8[$row->product_code]['b'] += 1;
            }
            // 失败订单
            if (in_array($row->status, [50, 51, 60])) {
                $data8[$row->product_code]['c'] += 1;
            }
//                    激活订单
            if ($row['activat_status'] == 1) {
                $data8[$row->product_code]['d'] += 1;
            }
//                    已充值订单
            if (intval($row['first_status']) == 1) {
                $data8[$row->product_code]['e'] += 1;
            }
        }
        return $this->returnMsg(200, '查询成功', $data8, $count);
    }

    //达人订单数据
    public function parseAnchorData($params, $authorIds)
    {
        $where = [];

        if (isset($params['dateRange']) && !empty($params['dateRange'])) {
            $params['dateRange'] = [date('Y-m-d', strtotime($params['dateRange'][0])), date('Y-m-d', strtotime($params['dateRange'][1])) . ' 23:59:59'];
            $where['between']['a.created_at'] = $params['dateRange'];
        }
        $where['in']['a.author_id'] = array_unique($authorIds);
        //关联主播时间数据
        $ModelAnchorWorks = new AnchorWorksModel();
        $ModelAnchor = new AnchorModel();
        $ModelAnchorAuthor = new AnchorAuthorModel();
//        查询开播数据
        $worksRows = [];
        foreach ($ModelAnchorWorks->from($ModelAnchorWorks->getTable() . ' AS a')
                     ->leftJoin($ModelAnchor->getTable() . ' AS b', 'a.anchor_id', '=', 'b.id')
                     ->leftJoin($ModelAnchorAuthor->getTable() . ' AS c', 'a.author_id', '=', 'c.author_id')
                     ->select('a.*', 'b.nickname AS anchor_name', 'c.nickname AS author_name')
                     ->searchWhere($where)
                     ->cursor() as $row) {
            $worksRows[] = $row;
        }
//        print_r($this->getLastSql());
        if (!empty($worksRows)) {
            $Repository = new AnchorStatsRepository();
            $Repository->countWorksOrdersData($worksRows);
        }
        //主播数据的统计,主播下有多个达人设计
        $anchorData = [];
        foreach ($worksRows as $k => $row) {
//            $anchorId=$row['anchor_id'];
            $anchorId = md5($row['anchor_id'] . $row['author_id']);
//                    主播头像
            $anchorData[$anchorId]['avatar'] = '';
//                    主播名字
            $anchorData[$anchorId]['nickname'] = $row['anchor_name'];

            //推广费用,推广费用使用每场输入的金额
            if (isset($anchorData[$anchorId]['a'])) {
                $anchorData[$anchorId]['a'] += round($row['cost'], 2);//$row['commission'] ?? 0;
            } else {
                $anchorData[$anchorId]['a'] = $row['cost'];// $row['commission'] ?? 0;
            }
            //销售订单
            if (isset($anchorData[$anchorId]['c'])) {
                $anchorData[$anchorId]['c'] += $row['sales'] ?? 0;
            } else {
                $anchorData[$anchorId]['c'] = $row['sales'] ?? 0;
            }
            //转化成本:推广费用/销售订单
            if ($anchorData[$anchorId]['c'] > 0) {
                $anchorData[$anchorId]['b'] = round($anchorData[$anchorId]['a'] / $anchorData[$anchorId]['c'], 2);
            } else {
                $anchorData[$anchorId]['b'] = 0;
            }
            //直播时长
            if (isset($anchorData[$anchorId]['d'])) {
                $anchorData[$anchorId]['d'] += $row['second'] ?? 0;
            } else {
                $anchorData[$anchorId]['d'] = $row['second'] ?? 0;
            }
            //重复订单
            if (isset($anchorData[$anchorId]['e'])) {
                $anchorData[$anchorId]['e'] += $row['repeat'] ?? 0;
            } else {
                $anchorData[$anchorId]['e'] = $row['repeat'] ?? 0;
            }
        }
        return $anchorData;
    }

//    归属客服报表
    public function kefuData($rows)
    {
        $data = [];
//        判断是否是同一个人重复下的单，相同的电话，地址，身份证都可视为同一个人
        $onlyIdentity = [];
        $onlyPhone = [];
        $onlyAddress = [];
        $ordersIds = [];
        foreach ($rows as $row) {
            $ordersIds[] = $row->id;
            $serviceId = $row->service_user_id;
//            初始化数据
            if (!isset($data[$serviceId])) {
                $only[$serviceId] = [];
                $onlyPhone[$serviceId] = [];
                $onlyAddress[$serviceId] = [];
                $data[$serviceId] = [];
            }
            //已分配订单数
            if (!isset($data[$serviceId]['a'])) {
                $data[$serviceId]['a'] = 1;
            } else {
                $data[$serviceId]['a'] += 1;
            }
            $hasRepeat = false;
            //            去重后的销量：即一个人只能一单
            if (isset($onlyIdentity[$serviceId]) && in_array($row->pay_identity, $onlyIdentity[$serviceId])) {
                $hasRepeat = true;
            } else {
                $onlyIdentity[$serviceId][] = $row->pay_identity;
            }
            //            再判断是否是相同电话
            if (isset($onlyPhone[$serviceId]) && in_array($row->pay_phone, $onlyPhone[$serviceId])) {
                $hasRepeat = true;
            } else {
                $onlyPhone[$serviceId][] = $row->pay_phone;
            }
//            再判断是否是相同地址
            $address = md5($row->post_province . $row->post_city . $row->post_area . $row->post_address);
            if (isset($onlyAddress[$serviceId]) && in_array($address, $onlyAddress[$serviceId])) {
                $hasRepeat = true;
            } else {
                $onlyAddress[$serviceId][] = $address;
            }
            //重复订单数
            if (true === $hasRepeat) {
                if (!isset($data[$serviceId]['b'])) {
                    $data[$serviceId]['b'] = 1;
                } else {
                    $data[$serviceId]['b'] += 1;
                }
            }
//            充值订单数
            if (intval($row->first_status) > 0) {
                if (!isset($data[$serviceId]['c'])) {
                    $data[$serviceId]['c'] = 1;
                } else {
                    $data[$serviceId]['c'] += 1;
                }
            }
            //            激活订单数
            if (intval($row->activat_status) > 0) {
                if (!isset($data[$serviceId]['d'])) {
                    $data[$serviceId]['d'] = 1;
                } else {
                    $data[$serviceId]['d'] += 1;
                }
            }
            //充值达标订单数
            if (intval($row->passing_money) > 0 && (intval($row->first_money) >= intval($row->passing_money))) {
                if (!isset($data[$serviceId]['e'])) {
                    $data[$serviceId]['e'] = 1;
                } else {
                    $data[$serviceId]['e'] += 1;
                }
            }
        }
//        相应的外呼数据
        $ModelTaskCall = new ServiceCallModel();
        $where = [];
        $where['in']['orders_id'] = $ordersIds;
        foreach ($ModelTaskCall->searchWhere($where)
                     ->select(['service_user_id', 'link_type', 'talk_time'])
                     ->cursor() as $row) {
            $serviceId = $row->service_user_id;
//            外呼总次数
            if (!isset($data[$serviceId]['f'])) {
                $data[$serviceId]['f'] = 1;
            } else {
                $data[$serviceId]['f'] += 1;
            }
//            接通次数
            if ($row->link_type == 1) {
                if (!isset($data[$serviceId]['g'])) {
                    $data[$serviceId]['g'] = 1;
                } else {
                    $data[$serviceId]['g'] += 1;
                }
            }
//            通话时长
            if (!isset($data[$serviceId]['h'])) {
                $data[$serviceId]['h'] = $row->talk_time;
            } else {
                $data[$serviceId]['h'] += $row->talk_time;
            }
        }
//        归属客服名字
        $ModelUsers = new AdminUsers();
        $where = [];
        $where['in']['id'] = array_keys($data);
        foreach ($ModelUsers->searchWhere($where)
                     ->select(['id', 'nick_name', 'avatar'])
                     ->cursor() as $row) {
            $serviceId = $row->id;
            $data[$serviceId]['nickname'] = $row->nick_name;
            $data[$serviceId]['avatar'] = $row->avatar;
        }
        return $data;
    }
}
